package com.xjm.bean.definition;

import com.xjm.model.Root;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author jaymin<br>
 * <p>
 * 2020/11/29 13:28
 */
@SuppressWarnings("all")
public class RootBeanDefinitionDemo {

	/**
	 * 通过构造器注入参数获取RootBeanDefinition
	 *
	 * @return
	 */
	public static RootBeanDefinition getRootBeanDefinitionByConstruct() {
		ConstructorArgumentValues cargs = new ConstructorArgumentValues();
		cargs.addIndexedArgumentValue(0, "rootA");
		cargs.addIndexedArgumentValue(1, "This is a RootBeanDefinition");
		cargs.addIndexedArgumentValue(2, true);
		RootBeanDefinition rootBeanDefinitionA = new RootBeanDefinition(Root.class, cargs, null);
		return rootBeanDefinitionA;
	}

	/**
	 * 通过Setter的方式注入参数,返回RootBeanDefinition
	 *
	 * @return
	 */
	public static RootBeanDefinition getRootBeanDefinitionBySetter() {
		MutablePropertyValues propertyValues = new MutablePropertyValues();
		propertyValues.addPropertyValue("name", "rootB");
		propertyValues.addPropertyValue("description", "This is a RootBeanDefinition");
		propertyValues.addPropertyValue("isRoot", true);
		RootBeanDefinition rootBeanDefinitionB = new RootBeanDefinition(Root.class, null, propertyValues);
		return rootBeanDefinitionB;
	}

	public static void main(String[] args) {
		// 1. 构建一个空的容器
		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
		// 2.创建一个RootBeanDefinition
		RootBeanDefinition rootBeanDefinitionA = getRootBeanDefinitionByConstruct();
		RootBeanDefinition rootBeanDefinitionB = getRootBeanDefinitionBySetter();
		applicationContext.registerBeanDefinition("rootA", rootBeanDefinitionA);
		applicationContext.registerBeanDefinition("rootB", rootBeanDefinitionB);
		// 这里埋一个点，直到这里才调用了Root对象的构造函数
		applicationContext.refresh();
		Root rootA = ((Root) applicationContext.getBean("rootA"));
		Root rootB = ((Root) applicationContext.getBean("rootB"));
		System.out.println(rootA.toString());
		System.out.println(rootB.toString());
	}
}
